package net.ankao.job.common;

import net.ankao.job.configuration.ServerJobConfig;
import net.ankao.job.core.rpc.IAkJobServerService;
import net.ankao.job.service.IAkApplicationClientService;
import net.ankao.job.service.IAkApplicationJobService;
import net.ankao.job.service.IAkApplicationService;
import net.ankao.job.service.IAkJobTaskService;
import net.ankao.job.service.impl.AkJobServerServiceImpl;
import net.ankao.job.utils.NetworkUtil;
import org.apache.commons.lang3.StringUtils;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * @author LILU
 * @date 2024-11-15 16:44
 */
public class RmiServerInit {

    private static final String SERVER_CLASS_NAME = "IAkJobServerService";


    private ServerJobConfig serverJobConfig;

    private IAkApplicationService akApplicationService;

    private IAkApplicationClientService akApplicationClientService;

    private IAkApplicationJobService applicationJobService;

    private IAkJobTaskService akJobTaskService;

    public void setAkApplicationService(IAkApplicationService akApplicationService) {
        this.akApplicationService = akApplicationService;
    }

    public void setAkApplicationClientService(IAkApplicationClientService akApplicationClientService) {
        this.akApplicationClientService = akApplicationClientService;
    }

    public void setApplicationJobService(IAkApplicationJobService applicationJobService) {
        this.applicationJobService = applicationJobService;
    }

    public void setAkJobTaskService(IAkJobTaskService akJobTaskService) {
        this.akJobTaskService = akJobTaskService;
    }

    public void setClientJobConfig(ServerJobConfig serverJobConfig) {
        this.serverJobConfig = serverJobConfig;
    }

    public void handle() throws RemoteException, MalformedURLException {
//        IAkJobServerService service = new AkJobServerServiceImpl();
        IAkJobServerService service = new AkJobServerServiceImpl(akApplicationService,akApplicationClientService,applicationJobService,akJobTaskService);

        if (StringUtils.isEmpty(serverJobConfig.getUrl())) {
            serverJobConfig.setUrl(NetworkUtil.getLocalIPv4Address().get());
        }
        if (serverJobConfig.getPort() == null) {
            serverJobConfig.setPort(9098);
        }
        LocateRegistry.createRegistry(serverJobConfig.getPort());
        Naming.rebind("//localhost:" + serverJobConfig.getPort() + "/" + SERVER_CLASS_NAME, service);
        System.out.println("Server is ready...");
    }
}
